package com.CityHunter.Fetcher;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.CityHunter.RoutePoint;
import com.google.android.maps.GeoPoint;

public class RoutePointFetcher {
	
	private static RoutePointFetcher ourInstance = new RoutePointFetcher();
	
	 public static RoutePointFetcher getInstance() {
	        return ourInstance;
	    }
	
	public List<RoutePoint> getRoutePoitList(GeoPoint start,GeoPoint end){
		String start_lat=String.valueOf(start.getLatitudeE6()/1000000);
		String start_lng=String.valueOf(start.getLongitudeE6()/1000000);
		String end_lat=String.valueOf(end.getLatitudeE6()/1000000);
		String end_lng=String.valueOf(end.getLongitudeE6()/1000000);
		 List<RoutePoint> rpList = new ArrayList<RoutePoint>();
		 HttpPost httpRequest = new HttpPost("http://maps.google.com.hk/maps/api/directions/json?origin="+start_lat+","+start_lng+"&destination="+end_lat+","+end_lng+"&sensor=false&mode=walking&language=zh-TW");
			DefaultHttpClient httpclient = new DefaultHttpClient();
			
				
				HttpResponse httpResponse = null;
				try {
					httpResponse = httpclient.execute(httpRequest);
					String strResult = EntityUtils.toString(httpResponse.getEntity());
				
					JSONObject result=new JSONObject(strResult);
					
					JSONArray routes=result.getJSONArray("routes");
					JSONObject routesObj=routes.getJSONObject(0);
					JSONArray legs=routesObj.getJSONArray("legs");
					JSONArray steps=legs.getJSONObject(0).getJSONArray("steps");
					String desc="";
					for(int i=0;i<steps.length();i++){
						JSONObject start_location=steps.getJSONObject(i).getJSONObject("start_location");
						JSONObject end_location=steps.getJSONObject(i).getJSONObject("end_location");
						
						desc=steps.getJSONObject(i).getString("html_instructions")+"\n";
						rpList.add(new RoutePoint(Double.valueOf(end_location.getString("lat")), Double.valueOf(end_location.getString("lng")), descriptionParser(desc)) );
					}
				
				} 
				catch(Exception e){
					Log.e("Error",e.toString());
					
				}
				
	return rpList;
		
	}
	
	
	public String descriptionParser(String result){
		String clear="";
		boolean ok=true;
		for(int ind=0;ind<result.length();ind++){
			if (result.charAt(ind)=='<')
				ok=false;
			else if(result.charAt(ind)=='>')
				ok=true;
			else if(ok==true)
				clear+=result.charAt(ind);
				
		}
		return clear;
	}

}
